package com.minelx.util.socket;

import com.minelx.util.IOUtil;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.function.Consumer;

public class TCPPortService {
	private final ExecutorService executorService;

	private final ServerSocket server;

	private final Consumer<byte[]> acceptor;

	public TCPPortService(int port, Consumer<byte[]> acceptor) throws IOException {
		this.acceptor = acceptor;
		executorService = Executors.newSingleThreadExecutor();
		this.server = new ServerSocket(port);
	}

	public void start() {
		executorService.submit(this::accepting);
	}

	public void stop() {
		executorService.shutdown();
		try {
			server.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void accepting() {
		System.out.println("start accepting...");
		try (Socket connection = server.accept()) {
			System.out.println("there goes a connection.");
			acceptor.accept(IOUtil.bytesOf(connection.getInputStream()));
		} catch (IOException e) {
			System.err.println("toward peer disconnected.");
		}
	}
}
